package com.example.barrage.handler;

import com.example.barrage.model.BarrageMessage;
import com.example.barrage.service.SensitiveWordService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentHashMap;

@Component
@io.netty.channel.ChannelHandler.Sharable
public class BarrageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(BarrageHandler.class);

    // 用于存储所有连接的通道组
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 存储用户信息
    private static ConcurrentHashMap<String, String> userMap = new ConcurrentHashMap<>();

    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired
    private SensitiveWordService sensitiveWordService;

    /**
     * 当客户端连接到服务器时触发
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        channels.add(incoming);
        logger.info("【WebSocket】客户端已连接 - IP地址: {}, 通道ID: {}", incoming.remoteAddress(), incoming.id().asLongText());
        logger.info("【WebSocket】当前在线客户端数量: {}", channels.size());
    }

    /**
     * 当客户端断开连接时触发
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        channels.remove(incoming);
        String userId = userMap.remove(incoming.id().asLongText());
        logger.info("【WebSocket】客户端已断开连接 - IP地址: {}, 通道ID: {}, 用户ID: {}", incoming.remoteAddress(), incoming.id().asLongText(), userId);
        logger.info("【WebSocket】剩余在线客户端数量: {}", channels.size());
    }

    /**
     * 处理接收到的文本消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Channel incoming = ctx.channel();
        String request = msg.text();
        
//        logger.debug("【WebSocket】收到来自客户端的消息 - 客户端IP: {}, 消息内容: {}", incoming.remoteAddress(), request);
//
//        try {
//            // 解析消息
//            BarrageMessage barrageMsg = objectMapper.readValue(request, BarrageMessage.class);
//
//            logger.info("【WebSocket】解析弹幕消息成功 - 用户ID: {}, 用户名: {}, 消息内容: {}",
//                barrageMsg.getUserId(), barrageMsg.getUsername(), barrageMsg.getContent());
//
//            // 检查敏感词
//            if (sensitiveWordService.containsSensitiveWords(barrageMsg.getContent())) {
//                logger.warn("【WebSocket】弹幕消息包含敏感词: {}", barrageMsg.getContent());
//                // 发送错误消息回客户端
//                ctx.writeAndFlush(new TextWebSocketFrame("Error: 消息包含敏感字符，发送失败"));
//                return;
//            }
//
//            // 设置服务器时间
//            barrageMsg.setTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//
//            // 广播消息给所有连接的客户端
//            broadcastMessage(barrageMsg);
//
//            logger.info("【WebSocket】弹幕消息广播完成 - 消息内容: {}, 来自客户端: {}, 广播给 {} 个客户端",
//                barrageMsg.getContent(), incoming.remoteAddress(), channels.size());
//        } catch (Exception e) {
//            logger.error("【WebSocket】解析消息失败: " + request, e);
//            // 发送错误消息回客户端
//            ctx.writeAndFlush(new TextWebSocketFrame("Error: 消息格式无效"));
//        }
        logger.warn("【WebSocket】拒绝处理来自客户端的直接消息 - 客户端IP: {}, 消息内容: {}",
                incoming.remoteAddress(), request);

        // 发送错误消息回客户端，告知必须通过HTTP API发送消息
        ctx.writeAndFlush(new TextWebSocketFrame(
                "Error: 为了安全考虑，客户端不能直接发送弹幕消息。请通过HTTP API (/send) 发送消息。"));
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("【WebSocket】发生异常", cause);
        ctx.close();
    }

    /**
     * 广播消息给所有连接的客户端
     *
     * @param message 弹幕消息
     */
    public void broadcastMessage(BarrageMessage message) {
        try {
            String jsonMessage = objectMapper.writeValueAsString(message);
            logger.debug("【WebSocket】准备广播JSON消息: {}", jsonMessage);
            TextWebSocketFrame frame = new TextWebSocketFrame(jsonMessage);
            channels.writeAndFlush(frame);
            logger.info("【WebSocket】弹幕消息广播成功 - 用户: {}, 内容: {}, 广播给 {} 个客户端", 
                message.getUsername(), message.getContent(), channels.size());
        } catch (Exception e) {
            logger.error("【WebSocket】广播消息失败", e);
        }
    }
}